package cat.joronya.supermanager;

import java.util.Calendar;
import java.util.GregorianCalendar;

import cat.joronya.supermanager.service.SupermanagerIntent;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.preference.PreferenceManager;
import android.util.Log;

public class BootCompletedReceiver extends BroadcastReceiver 
{
	public static final String TAG = "supermanager";
	
	@Override
	public void onReceive(Context context, Intent intent) 
	{
		// get preferences for cron customization
		SharedPreferences settings = 
			PreferenceManager.getDefaultSharedPreferences(context);

		// close changes notify. Set alarm for next day.
		scheduleClosedChangesNotification(context, settings);
		
		// schedule update if necessary
		scheduleUpdate(context, settings);
	}
	
	/**
	 * Check if update schedule is needed, and if so, do it.
	 * @param settings
	 */
	private void scheduleUpdate(Context context, SharedPreferences settings)
	{
		// cron update?
		if( !settings.getBoolean(Supermanager.PREFS_CRON_ENABLED, true) )
		{
			Log.d(TAG, "BootCompletedReceiver: data update not enabled, exiting.");
			return;
		}
		
		AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
		
		String username = settings.getString(Supermanager.PREFS_USERNAME, null);
   		String password = settings.getString(Supermanager.PREFS_PASSWORD, null);
   		
   		SupermanagerIntent superIntent = 
			new SupermanagerIntent(SupermanagerIntent.ACTION_SYNC,
					Supermanager.Home.CONTENT_URI, context, null);
   		superIntent.putExtra("cat.joronya.supermanager.login.username", username);
   		superIntent.putExtra("cat.joronya.supermanager.login.password", password);
   		superIntent.putExtra("cat.joronya.supermanager.fullupdate.shownotifications", false);
   		
   		// cron hour
   		String cronHour = settings.getString(Supermanager.PREFS_CRON_HOUR, "07");
   		
   		// programem avui a l'hora establerta
		Calendar now = GregorianCalendar.getInstance();
		Calendar gc = new GregorianCalendar(now.get(Calendar.YEAR), 
				now.get(Calendar.MONTH), 
				now.get(Calendar.DAY_OF_MONTH), 
				Integer.parseInt(cronHour),
				0);
		
		// si avui ja ha passat l'hora, la primera per dema
		if( gc.getTimeInMillis() < now.getTimeInMillis() )
			gc.add(Calendar.DAY_OF_MONTH, 1);
		
		PendingIntent newPending =  PendingIntent.getService(context, 0, superIntent, 0);
		
		// repetir l'alarma diariament, update diari
		alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, 
				gc.getTimeInMillis(), 1000*60*60*24, newPending);

		Log.d(TAG, "BootCompletedReceiver: update scheduled!");
	}
	
	/**
	 * Check if close changes notify is needed, and if so, do it.
	 * @param settings
	 */
	private void scheduleClosedChangesNotification(Context context, SharedPreferences settings)
	{
		// cron update?
		if( !settings.getBoolean(Supermanager.PREFS_DUETIME_NOTIFICATION_ENABLED, true) )
		{
			Log.d(TAG, "BootCompletedReceiver: duetime notification not enabled, exiting.");
			return;
		}

		AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
		
		String username = settings.getString(Supermanager.PREFS_USERNAME, null);
   		String password = settings.getString(Supermanager.PREFS_PASSWORD, null);
   		
   		// supermanager sync intent
		SupermanagerIntent superIntent = 
			new SupermanagerIntent(SupermanagerIntent.ACTION_VIEW,
					Supermanager.Home.CONTENT_URI, context, null);
		superIntent.putExtra("cat.joronya.supermanager.login.username", username);
		superIntent.putExtra("cat.joronya.supermanager.login.password", password);
		
		// creem el pending intent
		PendingIntent newPending =  PendingIntent.getService(context, 0, superIntent, 0);
		
		// notification hour
   		String notificationHour = settings.getString(Supermanager.PREFS_DUETIME_NOTIFICATION_HOUR, "04");
	   		
   		Cursor cursor = context.getContentResolver().query(
			Supermanager.Home.CONTENT_URI, 
			Supermanager.Home.PROJECTION, 
			Supermanager.Home.DUE_TIME+" > "+(System.currentTimeMillis()/1000), 
			null, 
			Supermanager.Home.DUE_TIME+" DESC");
			
		// hi ha alguna data? Hem arribat al moment de mostrar la notificacio que s'escaigui
		if( cursor.moveToFirst() )
		{
			// duetime - notificationHour
			long duetime = cursor.getInt(4);
			duetime -= (Integer.parseInt(notificationHour)*60*60);
				
			// programem l'alarma al duetime - hores abans
			alarmManager.set(AlarmManager.RTC_WAKEUP, duetime*1000, newPending);
				
			Log.d(TAG, "BootCompletedReceiver: notification alarm scheduled");
		}

		Log.d(TAG, "BootCompletedReceiver: duetime notification scheduled!");		
	}
}

